<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="充电站" prop="csName">
        <el-input
            v-model="queryParams.csName"
            placeholder="请输入充电站"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单时间" prop="scharging_date">
        <el-date-picker clearable
                        v-model="selectedMonth"
                        type="month"
                        value-format="YYYY-MM"
                        placeholder="请选择订单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="display:flex;flex-wrap: wrap;height: 400px;width: 1000px">
      <div style="display:flex;flex-direction: column;width: 200px;margin-left: 20px">
        <div class="a">
          <div>充电度数：</div>
          <div style="margin-top: -14px">{{chargingmouthData }}</div>
        </div>
        <div class="a">
          <div>充电时长：</div>
          <div style="margin-top: -14px">{{chargingmouthDuration}}</div>
        </div>
        <div class="a">
          <div>充电次数：</div>
          <div style="margin-top: -14px">{{chargingmouthCount}}</div>
        </div>
      </div>
      <div style="width: 300px;height: 200px;margin-left: 100px"><e-charts class="chart" :option="option" /></div>
      <div style="width: 300px;height: 500px;margin-left: 50px"><e-charts class="chart" :option="option1" /></div>
    </div>

<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="日期" align="center"  width="180">
        <template #default="scope">
          <!-- 直接使用charging_date字段 -->
          <span v-if="scope.row.charging_date">
              {{ formatDate(scope.row.charging_date) }}
         </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="充电度数" align="center" prop="stotal_charging_amount" />
      <el-table-column label="充电时长" align="center" prop="stotal_charging_duration" />
      <el-table-column label="充电次数" align="center" prop="scharging_count" />
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup name="Record">
import {  getRecord, delRecord, addRecord, updateRecord } from "@/api/system/record"
import {  listCdrecord } from "@/api/system/cdrecord"

import { selecttotal,selectalls} from "@/api/system/yunyingrecord"
import {ref} from "vue";
import {values} from "vuedraggable/dist/vuedraggable.common.js";

const { proxy } = getCurrentInstance()

const recordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 创建单独的月份选择变量
const selectedMonth = ref(getCurrentMonth())

//月冲度数
const chargingmouthData = ref([])
//月冲时长
const chargingmouthDuration = ref([])
//月冲次数
const chargingmouthCount = ref([])

// 支付类型
const payType = ref([])
// 8月充电次数-日期
const totalDate = ref([])

const totalData = ref([])

// 8月充电度数
const totalRechargeAmount = ref([])
// 8月充电时长
const totalRechargeTime = ref([])
const list = ref([])
const listst = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recordNumber: null,
    recordStationId: null,
    recordGunId: null,
    recordAmount: null,
    recordMoney: null,
    recordDuration: null,
    recordTime: null,
    cgName: null,
    csName: null,
    scharging_date: [],
    stotal_charging_duration: null,
    scharging_count: null,
    stotal_charging_amount: null,
    month: null
  },
  rules: {
  }
})
const maplist= ref([])
const tableDatas = ref([])


const { queryParams, form, rules } = toRefs(data)
const option = ref({
  title: {
    text: '充电情况'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['充电度数', '充电时长']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: totalDate
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '充电度数',
      type: 'line',
      smooth: true,
      data: totalRechargeAmount
    },
    {
      name: '充电时长',
      type: 'line',
      smooth: true,
      data: totalRechargeTime
    }
  ]
})

const option1 = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      // Use axis to trigger tooltip
      type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
    }
  },
  legend: {},
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: totalDate
  },
  series: [
    {
      name: '8月充电次数',
      type: 'bar',
      stack: 'total',
      label: {
        show: true
      },
      emphasis: {
        focus: 'series'
      },
      data: totalData
    },
  ]
});



onMounted(()=>{
  queryParams.value.month = getCurrentMonth(); // 初始化默认月份
  getList()
  getrecordlist()
  getweixinlis()
})
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}
function getweixinlis(){
  selecttotal().then(response =>{
    console.log(8888999777)
    console.log(response)
    payType.value = response.map(item => item.pay_count)

  })
}

function getCurrentMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
}


function getrecordlist(){
  // const month = queryParams.value.scharging_date || getCurrentMonth()
  listCdrecord(selectedMonth.value).then(response =>{
    if (response && response.length > 0) {
      // 处理有数据的情况...
      console.log(147159159)
      tableDatas.value = response
      listst.value = response
      console.log(response)
      // totalDate.value = listst.value.slice(0, 7).map(item => item.scharging_date)
      const month = selectedMonth.value.split('-')[1].replace(/^0/, ''); // 去掉前导零
      option1.value.series[0].name = `${month}月充电次数`; // 更新系列名称
      totalData.value =listst.value.map(item => item.scharging_count)
      totalRechargeAmount.value =listst.value.map(item => item.stotal_charging_amount)
      totalRechargeTime.value = listst.value.map(item => item.stotal_charging_duration)

      queryParams.value.scharging_date = response.map(item => item.scharging_date); // 日期数组
      queryParams.value.stotal_charging_amount = response.map(item => item.stotal_charging_amount); // 充电度数数组
      queryParams.value.stotal_charging_duration = response.map(item => item.stotal_charging_duration); // 充电时长数组
      queryParams.value.scharging_count = response.map(item => item.scharging_count); // 充电时长数组


    } else {
      // 清空所有图表数据
      tableDatas.value = [];
      listst.value = [];
      totalDate.value = [];
      totalData.value = [];
      totalRechargeAmount.value = [];
      totalRechargeTime.value = [];

      // 重置汇总数据
      chargingmouthData.value = 0;
      chargingmouthDuration.value = 0;
      chargingmouthCount.value = 0;
    }
  }).catch(error => {
    console.error("获取图表数据失败:", error);
    // 清空图表数据
    totalDate.value = [];
    // ...其他清空操作...
  })


}


// 修改handleQuery函数
function handleQuery() {
  if (!queryParams.value.month) {
    queryParams.value.month = getCurrentMonth();
  }
  queryParams.value.pageNum = 1;
  getList();
  getrecordlist(queryParams.value.scharging_date || getCurrentMonth(),queryParams.value.csName);
}

// 修改onMounted，初始化时传入当前月份
// onMounted(() => {
//   const currentMonth = getCurrentMonth();
//   queryParams.value.scharging_date = currentMonth; // 设置默认值为当前月
//   getList();
//   getrecordlist(currentMonth);
//   getweixinlis();
// });



/** 查询充电记录列表 */
function getList() {
  loading.value = true
  // 设置查询参数中的月份
  queryParams.value.month = selectedMonth.value;
  listCdrecord( queryParams.value.month,queryParams.value.csName).then(response => {
    // console.log(888888888888887652321)
    // recordList.value = response
    if (response && response.length > 0) {
      recordList.value = response;

      // 处理表格数据...

      totalDate.value = recordList.value.map(item => item.charging_date)
      totalData.value = recordList.value.map(item => item.scharging_count)
      totalRechargeAmount.value = recordList.value.map(item => item.stotal_charging_amount)

      // 8月充电时长
      totalRechargeTime.value = recordList.value.map(item => item.stotal_charging_duration)

      //月冲度数
      chargingmouthData.value = recordList.value.reduce((sum, item) => sum + parseFloat(item.stotal_charging_amount), 0).toFixed(2); // 返回字符串，如 "123.45"
      // chargingmouthData.value = recordList.value.reduce((sum,item)=>(sum+parseFloat(item.stotal_charging_amount)),0)
      //月冲时长
      chargingmouthDuration.value = recordList.value.reduce((sum,item)=>sum+parseFloat(item.stotal_charging_duration),0)
      //月冲次数
      chargingmouthCount.value = recordList.value.reduce((sum,item)=>sum+Number(item.scharging_count),0)

      total.value = response.total
      loading.value = false
    } else {
      // 清空表格数据
      recordList.value = [];
      total.value = 0;

      // 清空图表数据
      totalDate.value = [];
      totalData.value = [];
      totalRechargeAmount.value = [];
      totalRechargeTime.value = [];

      // 清空汇总数据
      chargingmouthData.value = 0;
      chargingmouthDuration.value = 0;
      chargingmouthCount.value = 0;
    }
    loading.value = false;
  }).catch(error => {
    console.error("获取数据失败:", error);
    loading.value = false;
    // 清空所有数据
    recordList.value = [];
    totalDate.value = [];
    // ...其他清空操作...
  });

}
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.csName = ""; // 明确清空充电站
  selectedMonth.value = getCurrentMonth(); // 重置为当前月份
  handleQuery();
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    recordNumber: null,
    recordStationId: null,
    recordGunId: null,
    recordAmount: null,
    recordMoney: null,
    recordDuration: null,
    recordTime: null,
    chargingGun: {
      cgId: null,
      cgName: null
    },
    chargingStation: {
      csId: null,
      cgName: null
    }
  }
  proxy.resetForm("recordRef")
}

/** 搜索按钮操作 */
//

/** 重置按钮操作 */
// function resetQuery() {
//   proxy.resetForm("queryRef")
//   queryParams.value.csName = ''; // 明确清空充电站查询条件
//   queryParams.value.month = getCurrentMonth(); // 重置为当前月份
//   handleQuery();
//   handleQuery()
// }
//
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// /** 新增按钮操作 */
// function handleAdd() {
//   reset()
//   open.value = true
//   title.value = "添加充电记录"
// }
//
// /** 修改按钮操作 */
// function handleUpdate(row) {
//   reset()
//   const _recordId = row.recordId || ids.value
//   getRecord(_recordId).then(response => {
//     form.value = response.data
//     open.value = true
//     title.value = "修改充电记录"
//   })
// }
//
// /** 提交按钮 */
// function submitForm() {
//   proxy.$refs["recordRef"].validate(valid => {
//     if (valid) {
//       if (form.value.recordId != null) {
//         updateRecord(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addRecord(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }



getList()
</script>
<style>
.chart {

  height: 300px;
}
.a{
  margin-top: 20px;
  height: 80px;
  text-align: center;
  line-height: 50px;
  background: linear-gradient(to right, rgba(0, 0, 255, 0.5), rgba(0, 128, 255, 0.5));
}
</style>
